package com.clss.uvctest

import android.Manifest
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.widget.Button
import android.widget.Toast


class MainActivity_ : AppCompatActivity() {

    companion object {
        const val TAG = "MainActivity"
        const val ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"
    }

    lateinit var usbManager : UsbManager
    var mPermissionIntent : PendingIntent? = null
    val usbReceiver = USBReceiver()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//        findViewById<Button>(R.id.button_id).setOnClickListener {
//            checkDevice()
//        }
        requestPermissions(arrayOf(Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
        usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
    }

    fun checkDevice(){
        val usbDevices = getDeviceList()
        if (usbDevices.size > 0){
            val usbDevice = usbDevices[0]
            requestPermission(usbDevice)
        }
    }

    fun getDeviceList(): List<UsbDevice> {
        val deviceList = usbManager.deviceList
        val deviceIterator: Iterator<UsbDevice> = deviceList.values.iterator()
        val usbDevices: MutableList<UsbDevice> = ArrayList()
        while (deviceIterator.hasNext()) {
            val device = deviceIterator.next()
            usbDevices.add(device)
            Log.i(TAG, "getDeviceList: " + device)
        }
        return usbDevices
    }

    /**
     * 判断对应 USB 设备是否有权限
     */
    fun hasPermission(device: UsbDevice): Boolean {
        return usbManager.hasPermission(device)
    }

    /**
     * 请求获取指定 USB 设备的权限
     */
    fun requestPermission(device: UsbDevice) {
        Log.i(TAG, "requestPermission: " + device)

        if (hasPermission(device)) {
            Toast.makeText(this, "已经获取到权限", Toast.LENGTH_SHORT).show()
        } else {
            if (mPermissionIntent == null) {
                registerReceiver()
            }
            usbManager.requestPermission(device, mPermissionIntent)
        }

    }

    fun registerReceiver() {
        Log.i(TAG, "---onReceive===")
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, Intent(ACTION_USB_PERMISSION), 0)
        val filter = IntentFilter(ACTION_USB_PERMISSION)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
        this.registerReceiver(usbReceiver, filter)
    }

    inner class USBReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            val action = intent.action
            Log.i(TAG, "---onReceive===$action")
            if (ACTION_USB_PERMISSION == action) {
                // 获取权限结果的广播
                synchronized(this) {
                    val device =
                            intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
                    Log.i(TAG, "---device != null===${device != null}")

                    if (device != null) {
                        Log.i(TAG, "---device.productId===${device.productId}")
                        //call method to set up device communication
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            Log.i(TAG, "获取权限成功：" + device.deviceName)
                        } else {
                            Log.i(TAG, "获取权限失败：" + device.deviceName)
                        }
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action) {
                // 有新的设备插入了，在这里一般会判断这个设备是不是我们想要的，是的话就去请求权限
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED == action) {
                // 有设备拔出了
            }
        }
    }
}